#SKU序列化器
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer

from apps.goods.models import SKU, SPU, GoodsCategory, SKUSpecification
from apps.meiduo_admin.serializers.all import SPU_specification_serializer, SpecificationOption_serializer, \
    ADD_SpecificationOption_serializer
from celery_tasks.sku_html.tasks import details_staticlize


class SKUSpecificationSerialzier(serializers.ModelSerializer):
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()
    class Meta:
        model = SKUSpecification  # SKUSpecification中sku外键关联了SKU表
        fields = ['spec_id','option_id']
class SKUSerializer(ModelSerializer):
    #spu是外键
    spu = serializers.StringRelatedField(read_only=True)#只允许读不许写入否则报错
    category = serializers.StringRelatedField(read_only=True)
    #还会传入一个spu_id 和 三级分类id 和规格选项
    spu_id = serializers.IntegerField()
    category_id = serializers.IntegerField()
    specs = SKUSpecificationSerialzier(many=True)
    class Meta:
        model = SKU
        fields = '__all__'

    #自定义创建
    def create(self, validated_data):
        #获取请求中发送过来的specs数据
        data = self.context['request'].data
        specs = data.get('specs')
        #因为前端传过来的specs格式无法写入 所以要删除掉
        if 'specs' in validated_data:
            del validated_data['specs']
        sku = SKU.objects.create(**validated_data)
        #手动创建specs sku规格表中
        for item in specs:
            SKUSpecification.objects.create(
                sku=sku,
                spec_id=item.get('spec_id'),
                option_id=item.get('option_id')
            )
        return sku
    def update(self, instance, validated_data):
        #将传入的specs删除  因为不支持多个传入
        data = self.context['request'].data
        #删除原有无法写入的specs
        if 'specs' in validated_data:
            del validated_data['specs']
        #删除后可以先修改sku表,获取指定的pk,更新的话注意要修改id为pk的
        pk = self.context['view'].kwargs['pk']
        sku = SKU.objects.filter(id=pk).update(**validated_data)
        #手动从请求中获取specs
        specs = data.get('specs')
        for spec in specs:
            SKUSpecification.objects.filter(sku_id=pk,spec_id=spec.get('spec_id')).update(
                option_id=spec.get('option_id')
            )
        #生成静态页面 用异步任务celery 生成,前端可以直接返回修改成功
        details_staticlize.delay(pk)
        return instance



#新增商品中的三级分类
class catagory_serializer(ModelSerializer):
    class Meta:
        model = GoodsCategory
        fields = '__all__'
# 新增商品中的SPU信息
class Add_SPU_serializer(ModelSerializer):
    class Meta:
        model = SPU
        fields = ['id','name']

